package com.jksoft.darewayyyy.util;

import android.util.Log;

import com.google.gson.Gson;
import com.jksoft.darewayyyy.global.MyApplication;
import com.jksoft.darewayyyy.pojo.Employee;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2015/12/10.
 */
public class PushServiceThread extends Thread{
    //
    String empId;

    PushServiceInterface pi;

    public void setPushListener(PushServiceInterface pi){
        this.pi = pi;
    }

    public interface PushServiceInterface {

        void onSuccess(Employee e);

    }

    public PushServiceThread(){
        tellIpToServer();
    }
    public PushServiceThread(String empId){
        this.empId = empId;
        tellIpToServer();
    }

    public void tellIpToServer(){
        // 告诉服务器自己的Ip地址
        String serverIp = "http://10.1.98.62:9090/dwCard/hello.do";
        try {
                OkHttpClientManager okHttpClientManager = OkHttpClientManager.getInstance();
                OkHttpClientManager.Param params[] = new OkHttpClientManager.Param[1];
                params[0] = new OkHttpClientManager.Param("a","1");
                okHttpClientManager.getPostDelegate().postAsyn(serverIp, params, new OkHttpClientManager.ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(String response) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

    public void run(){
        ServerSocket server = null;
        try{
            server = new ServerSocket(23456);
            while(true){
                Socket client = server.accept();//接收客户端请求
                BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                String line = null;
                StringBuffer sb = new StringBuffer();
                while((line = br.readLine()) != null){
                    sb.append(line);
                }
                client.close();
                Gson gson = new Gson();
                Employee employee = gson.fromJson(sb.toString(), Employee.class);
                // 给另一个线程处理
                pi.onSuccess(employee);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
